<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.name"
        placeholder="请输入企业名称"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >
        搜索
      </el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
        v-if="$hasPerm('sys:company:save')"
      >
        添加
      </el-button>
      <el-button
        v-waves
        :loading="downloadLoading"
        class="filter-item"
        type="primary"
        icon="el-icon-download"
        @click="handleDownload"
      >
        导出表格
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="序号" type="index"></el-table-column>
      <el-table-column label="企业名称" prop="name"></el-table-column>
      <el-table-column label="版本" prop="version"></el-table-column>
      <el-table-column label="联系电话" prop="phone"></el-table-column>
      <el-table-column label="到期时间" prop="expirationDate"></el-table-column>
      <el-table-column label="状态" v-if="$hasPerm('sys:company:update')">
        <template slot-scope="{ row }">
          <el-switch
            v-model="row.state"
            active-color="#13ce66"
            :active-text="row.state === 1 ? '正常' : ''"
            :active-value="1"
            inactive-color="#ff4949"
            :inactive-text="row.state === 1 ? '' : '停用'"
            :inactive-value="2"
            @change="changeState(row.id, row.state)"
          >
          </el-switch>
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        width="230"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row }">
          <el-button size="mini" @click="showDetail(row.id)">
            查看
          </el-button>
          <el-button
            type="primary"
            size="mini"
            @click="handleUpdate(row)"
            v-if="$hasPerm('sys:company:update')"
          >
            编辑
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      width="50%"
      @close="cleanFormData"
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="form"
        label-position="left"
        label-width="85px"
        style="width: 80%; margin-left:50px;"
      >
        <el-form-item label="公司名称:" prop="name">
          <el-input v-model="form.name" placeholder="请输入公司名称" />
        </el-form-item>
        <el-form-item label="登录账号:" prop="managerId">
          <el-input v-model="form.managerId" />
        </el-form-item>
        <el-form-item label="当前版本:" prop="version">
          <el-input v-model="form.version" />
        </el-form-item>
        <el-form-item label="续期时间:" prop="renewalDate">
          <el-date-picker
            v-model="form.renewalDate"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择续期时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="到期时间:" prop="expirationDate">
          <el-date-picker
            v-model="form.expirationDate"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择到期时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="所在地区:" prop="area">
          <el-cascader
            v-model="districts"
            :options="districtList"
            :props="districtOptions"
            placeholder="请选择公司所在地区"
            style="width: 100%"
            @change="setDistrict"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="详细地址:" prop="address">
          <el-input v-model="form.address" />
        </el-form-item>
        <el-form-item label="法人代表:" prop="legalRepresentative">
          <el-input v-model="form.legalRepresentative" />
        </el-form-item>
        <el-form-item label="电话:" prop="phone">
          <el-input v-model="form.phone" />
        </el-form-item>
        <el-form-item label="邮箱:" prop="email">
          <el-input v-model="form.email" />
        </el-form-item>
        <el-form-item label="公司规模:" prop="size">
          <el-input v-model="form.size" />
        </el-form-item>
        <el-form-item label="所属行业:" prop="industry">
          <el-cascader
            v-model="industries"
            :props="industryOptions"
            :placeholder="this.form.industryName || '请选择所属行业'"
            style="width: 100%"
            class="industry"
            @change="setIndustry"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="余额:" prop="balance">
          <el-input v-model="form.balance" />
        </el-form-item>
        <el-form-item label="备注:" prop="remarks">
          <el-input
            type="textarea"
            :maxlength="500"
            show-word-limit
            resize="none"
            v-model="form.remarks"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? createData() : updateData()"
        >
          确认
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table
        :data="pvData"
        border
        fit
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false"
          >确定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  fetchList,
  createCompany,
  updateCompany,
  fetchDistricts,
  subData
} from "@/api/company";
import waves from "@/directive/waves"; // waves directive
import { parseTime, cleanEmptyValue } from "@/utils";
// import { mapGetters } from 'vuex'
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination

export default {
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: "success",
        draft: "info",
        deleted: "danger"
      };
      return statusMap[status];
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type];
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10,
        name: null
        // importance: undefined,
        // title: undefined,
        // type: undefined,
        // sort: "+id"
      },
      importanceOptions: [1, 2, 3],

      sortOptions: [
        { label: "ID Ascending", key: "+id" },
        { label: "ID Descending", key: "-id" }
      ],
      statusOptions: ["published", "draft", "deleted"],
      showReviewer: false,
      form: {
        id: null,
        name: null,
        managerId: null,
        version: null,
        renewalDate: null,
        expirationDate: null,
        area: null,
        address: null,
        legalRepresentative: null,
        phone: null,
        email: null,
        size: null,
        industry: null,
        balance: null,
        remarks: null
      },
      rules: {
        name: [{ required: true, message: "必填项", trigger: "blur" }],
        managerId: [{ required: true, message: "必填项", trigger: "blur" }],
        renewalDate: [{ required: true, message: "必填项", trigger: "blur" }],
        expirationDate: [
          { required: true, message: "必填项", trigger: "blur" }
        ],
        area: [{ required: true, message: "必填项", trigger: "blur" }],
        address: [{ required: true, message: "必填项", trigger: "blur" }],
        legalRepresentative: [
          { required: true, message: "必填项", trigger: "blur" }
        ],
        phone: [
          { required: true, message: "必填项", trigger: "blur" },
          {
            pattern: /(^1[3456789]\d{9}$)|(^0\d{2,3}-?\d{7,8}$)/,
            message: "请输入正确的手机号或者座机号",
            trigger: "blur"
          }
        ],
        邮箱: [
          { type: "email", message: "请输入正确的邮箱格式", trigger: "blur" }
        ]
      },
      districts: [],
      districtList: [],
      districtOptions: {
        value: "name",
        label: "name",
        expandTrigger: "hover"
      },
      industries: [],
      industryOptions: {
        lazy: true,
        async lazyLoad(node, resolve) {
          // console.log(node, "node");
          const { root, level } = node;
          let id = 0;
          if (!root) {
            id = node.value;
          }
          let { industries } = await subData(id);
          industries = industries.map(item => ({
            value: item.id,
            label: item.name,
            leaf: level >= 3
          }));
          resolve(industries);
        }
      },
      state: true,
      dialogFormVisible: false,
      dialogStatus: "",
      textMap: {
        update: "修改",
        create: "添加"
      },
      dialogPvVisible: false,
      pvData: [],

      downloadLoading: false
    };
  },
  // computed: {
  //   ...mapGetters([
  //     btns
  //   ])
  // },
  created() {
    this.getList();
    this.queryDistricts();
  },
  methods: {
    getList() {
      this.listLoading = true;
      if (!this.listQuery.name) {
        delete this.listQuery.name;
      }
      fetchList(this.listQuery).then(response => {
        // console.log(response);
        this.list = response.page.list;
        this.total = response.page.totalCount;
        this.listLoading = false;
      });
    },

    changeState(id, state) {
      updateCompany({ id, state }).then(resp => {
        this.getList();
      });
    },
    showDetail(id) {
      this.$router.push(`/company/companyDetail/${id}`);
    },
    handleFilter() {
      this.getList();
    },
    queryDistricts() {
      fetchDistricts(3).then(resp => {
        this.districtList = resp.districts;
      });
    },

    handleModifyStatus(row, status) {
      this.$message({
        message: "操作Success",
        type: "success"
      });
      row.status = status;
    },
    sortChange(data) {
      const { prop, order } = data;
      if (prop === "id") {
        this.sortByID(order);
      }
    },
    sortByID(order) {
      if (order === "ascending") {
        this.listQuery.sort = "+id";
      } else {
        this.listQuery.sort = "-id";
      }
      this.handleFilter();
    },
    handleCreate() {
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    setDistrict(v) {
      // console.log(v);
      this.form.area = v.join("-");
      // console.log(this.area, 'area');
    },
    setIndustry(v) {
      // console.log(v);
      this.form.industry = v.join("-");
      // console.log(this.industry, 'industry');
    },

    createData() {
      // console.log(this.form);
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          cleanEmptyValue(this.form);
          createCompany(this.form).then(() => {
            this.dialogFormVisible = false;
            this.getList();
          });
        }
      });
    },

    handleUpdate(row) {
      this.form = Object.assign({}, row); // copy obj
      this.districts = this.form.area.split("-");
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    updateData() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          cleanEmptyValue(this.form);
          updateCompany(this.form).then(() => {
            this.getList();
            this.dialogFormVisible = false;
          });
        }
      });
    },
    cleanFormData() {
      this.$refs["dataForm"].resetFields();
      this.districts = [];
      this.industries = [];
    },
    handleFetchPv(pv) {
      fetchPv(pv).then(response => {
        this.pvData = response.data.pvData;
        this.dialogPvVisible = true;
      });
    },
    handleDownload() {
      this.downloadLoading = true;
      import("@/vendor/Export2Excel").then(excel => {
        const tHeader = ["timestamp", "title", "type", "importance", "status"];
        const filterVal = [
          "timestamp",
          "title",
          "type",
          "importance",
          "status"
        ];
        const data = this.formatJson(filterVal);
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: "table-list"
        });
        this.downloadLoading = false;
      });
    },
    formatJson(filterVal) {
      return this.list.map(v =>
        filterVal.map(j => {
          if (j === "timestamp") {
            return parseTime(v[j]);
          } else {
            return v[j];
          }
        })
      );
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort;
      return sort === `+${key}` ? "ascending" : "descending";
    }
  }
};
</script>
<style scoped>
/deep/ .industry input::-webkit-input-placeholder {
  color: #717171 !important;
}
/deep/ .industry input::-moz-placeholder {
  /* Mozilla Firefox 19+ */
  color: #717171 !important;
}
/deep/ .industry input:-moz-placeholder {
  /* Mozilla Firefox 4 to 18 */
  color: #717171 !important;
}
/deep/ .industry input:-ms-input-placeholder {
  /* Internet Explorer 10-11 */
  color: #717171 !important;
}
</style>
